<?php


namespace Soen\Filesystem;


use FilesystemIterator;
use Soen\Filesystem\Exception\FileException;

class File
{
    public $dirPath;
    /**
     * @var FilesystemIterator
     */
    public $filesystemIterator;
	/**
	 * @var FilesystemIterator[]
	 */
    public $files = [];
    function __construct()
    {
    }
    public function setDirPath(string $dir){
        if(!is_dir($dir)) {
            throw new FileException('不是目录', 0);
        }
        $this->dirPath = $dir;
    }

    function createFilesystemIterator(string $dir){
        $this->setDirPath($dir);
        $this->filesystemIterator = new FilesystemIterator($this->dirPath, FilesystemIterator::CURRENT_AS_SELF);
        return $this;
    }

    function getFilesystemIterator(){
        return $this;
    }

    /**
     * 处理扫描的 目录中的文件
     * @param callable|null $func
     * @param FilesystemIterator|null $filesystemIterator
     * @return File
     */
    function scanFiles(callable $func = null, FilesystemIterator $filesystemIterator = null):self {
	    if(!$filesystemIterator){
		    $filesystemIterator = $this->filesystemIterator;
	    }
	    while ($filesystemIterator->valid()){
		    if($filesystemIterator->isDir()){
			    $this->readArrayFilesDeep(new FilesystemIterator($filesystemIterator->key()));
		    } else {
                $func($filesystemIterator);
//			    $filePath = $filesystemIterator->getPathname();
//			    if($filesystemIterator->getExtension() === 'php') {
//				    $array[] = require_once $filePath;
//			    }
		    }
		    $filesystemIterator->next();
	    }
	    return $this;
    }

	/**
	 * 引入扫描到的php文件
	 */
    function readFilesRequire(){
		foreach ($this->files as $file){
		    $filePath = $file->getPathname();
		    if($file->getExtension() === 'php') {
			    require_once $filePath;
		    }
		}
		return $this;
    }

	/**
	 * 获取每个文件的名字
	 * @return array
	 */
    public function getFilesName(){
    	$filesName = [];
	    foreach ($this->files as $file){
		    $filesName[] = $file->getFilename();
	    }
	    return $filesName;
    }

    /**
     * @param FilesystemIterator $filesystemIterator
     * @param array $array
     * @return array
     */
    function readArrayFilesDeep(FilesystemIterator $filesystemIterator = null, &$array = []):array {
        if(!$filesystemIterator){
            $filesystemIterator = $this->filesystemIterator;
        }
        while ($filesystemIterator->valid()){
            if($filesystemIterator->isDir()){
                $this->readArrayFilesDeep(new FilesystemIterator($filesystemIterator->key()), $array);
            } else {
                $filePath = $filesystemIterator->getPathname();
                if($filesystemIterator->getExtension() === 'php') {
                    $array[] = require_once $filePath;
                }
            }
            $filesystemIterator->next();
        }
        return $array;
    }
}